import { useLocation } from "react-router-dom";
import { useMemo } from "react";

/**
 * Hook to get URL query parameters
 * @returns An object containing all query parameters
 * 
 * @example
 * // For URL: /page?name=John&age=25
 * const query = useRouterQuery();
 * console.log(query.name); // "John"
 * console.log(query.age); // "25"
 */
export const useRouterQuery = () => {
  const { search } = useLocation();

  return useMemo(() => {
    const params = new URLSearchParams(search);
    return Object.fromEntries(params.entries());
  }, [search]);
};

/**
 * Hook to get a specific query parameter
 * @param key - The query parameter key to get
 * @returns The value of the query parameter, or undefined if not found
 * 
 * @example
 * // For URL: /page?name=John&age=25
 * const name = useRouterQueryParam('name'); // "John"
 * const email = useRouterQueryParam('email'); // undefined
 */
export const useRouterQueryParam = (key: string) => {
  const { search } = useLocation();
  
  return useMemo(() => {
    const params = new URLSearchParams(search);
    return params.get(key) || undefined;
  }, [search, key]);
};

/**
 * Hook to get multiple query parameters
 * @param keys - Array of query parameter keys to get
 * @returns An object containing the requested query parameters
 * 
 * @example
 * // For URL: /page?name=John&age=25&city=NY
 * const { name, age } = useRouterQueryParams(['name', 'age']);
 * console.log(name); // "John"
 * console.log(age); // "25"
 */
export const useRouterQueryParams = <T extends string>(keys: T[]) => {
  const { search } = useLocation();
  
  return useMemo(() => {
    const params = new URLSearchParams(search);
    const result = {} as Record<T, string | undefined>;
    
    keys.forEach(key => {
      result[key] = params.get(key) || undefined;
    });
    
    return result;
  }, [search, keys]);
};
